﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Web.Services;
using App.Core.Extensions;
using App.Data;
using App.Core.DB;


public partial class Pages_Public_CompanyProfile : BasePage
{
    protected int _CustomerID = 0;
    protected bool _IsDeveloper = false;
    protected List<PropertyType> _PropertyTypes = new List<PropertyType>();

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindCompanyInfo();
        }
    }
    protected void BindPageInfo()
    {
        _CustomerID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }
    protected void BindCompanyInfo()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var customer = context.Customers.FirstOrDefault(C => C.ID == _CustomerID);
        if (customer == null)
            ShowNotFoundMessage();
        else
        {
            if (SessionCache.CurrentUser != null && SessionCache.CurrentUser.GroupID == ConfigReader.IndividualUserGroupID)
                txtFromEmail.Text = SessionCache.CurrentUser.LoginName;

            if (customer.BusinessTypeID == ConfigReader.DeveloperBusinessTypeID)
                _IsDeveloper = true;

            _PropertyTypes = context.PropertyTypes.Where(P => P.ID != ConfigReader.OtherPropertyTypeID).ToList();
            ltrCompanyName.Text = customer.Name;
            ltrHeadingCompanyName.Text= ltrCompanyName.Text;
            if (!customer.Logo.IsNullOrEmpty())
            {
                imgCompanyLogo.ImageUrl = String.Format("{0}/{1}", AppConstants.CUSTOMER_LOGO, customer.Logo);           
                imgCompanyLogo.ToolTip = imgCompanyLogo.AlternateText = String.Format("{0} Logo", customer.Name.HtmlEncode());
                imgCompanyLogo.Visible = true;
            }
            ltrAboutUs.Text = WebUtil.FormatText(customer.About);
            if (!customer.WebSite.IsNullOrEmpty())
            {
                hplWebSite.NavigateUrl = WebUtil.GetCompleteUrl(customer.WebSite);
                hplWebSite.Visible = true;
            }
            ///Bind Addresses
            var addresses = from P in context.Addresses where P.CustomerID == _CustomerID select P;
            if (addresses != null && addresses.Count() > 0)
            {
                List<Address> addressList = addresses.ToList();
                if (addressList.Count == 1)
                {
                    BindCompanyAddress(addressList[0]);
                    //chkIsBillingAddress.Checked = true;
                }
                else
                {
                    Address companyAddress = addressList.FirstOrDefault(A => A.IsBillingAddress == false);
                    BindCompanyAddress(companyAddress);
                    Address billingAddress = addressList.FirstOrDefault(A => A.IsBillingAddress == true);
                    BindBillingAddress(billingAddress);
                }
            }
            ///Bind Contacts
            UtilityDAO dao = new UtilityDAO();
            App.Data.DbParameter[] parameters = new[] { new App.Data.DbParameter("@CustomerID", _CustomerID) };
            DataSet ds = dao.GetDataSet(AppSQL.GET_CUSTOMER_CONTACTS, parameters, false);
            rptContacts.DataSource = ds.Tables[0];
            rptContacts.DataBind();
            ///Bind Hot Projects
            BindHotProjects(context);            
        }
    }
    protected void BindHotProjects(BtcHousingEntities context)
    {
        StringBuilder sb = new StringBuilder();
        String html = @"<div style='margin-bottom:10px;'>
                            <div>
                                <a href='{0}?ID={1}'>
                                    <img class='ProjectThumbImage' src='{2}/{1}/{3}' alt='Featured Project' title='Hot Project' />
                                </a>
                            </div>
                            <div class='GreenLink'><a href='{0}?ID={1}'>Featured Project {4}</a></div>
                        </div>";
        var projectQuery = from P in context.Projects where P.CustomerID == _CustomerID && !P.IsDeleted && P.IsHot select P;
        if (projectQuery != null && projectQuery.Count() > 0)
        {
            List<Project> projects = projectQuery.ToList();
            int counter = 1;
            foreach (Project project in projects)
            {
                var imageQuery = from P in context.ProjectFiles 
                                 where P.ProjectID == project.ID                                  
                                 && P.FileTypeID != ConfigReader.ProjectBrocheureFileTypeID
                                 select P;
                if(imageQuery != null && imageQuery.Count() > 0)
                {
                    ProjectFile file = imageQuery.ToList()[0];
                    sb.AppendFormat(html, AppConstants.Pages.PROJECT_DETAILS, project.ID
                        , AppConstants.PROJECT_FILES, file.ThumbFileName, counter);
                    
                    counter++;
                }
            }
            ltrHotProjects.Text = sb.ToString();
        }
    }
    protected void ShowNotFoundMessage()
    {
        WebUtil.ShowMessageBox(divMessage, "Sorry! requested company was not found.", true);
        pnlFormContainer.Visible = false;
    }
    protected void BindCompanyAddress(Address companyAddress)
    {        
        String country = companyAddress.City.Country.Name;
        String city = companyAddress.City.Name;
        StringBuilder streeAddress = new StringBuilder(companyAddress.StreetAddress.HtmlEncode());
        if (streeAddress.Length > 0 && !companyAddress.ZipCode.IsNullOrEmpty())
            streeAddress.Append(", ");
        streeAddress.Append(companyAddress.ZipCode.HtmlEncode());
        if (streeAddress.Length > 0)
            streeAddress.Append("<br />");

        //spanLocation.InnerHtml = String.Format("<br />{0}{1}, {2}", streeAddress.ToString(), city, country);
        ltrLocation.Text = String.Format("{0}{1}, {2}", streeAddress.ToString(), city, country);

        StringBuilder sb = new StringBuilder();
        String html = @"<tr>
					        <td><b>{0}</b></td>
					        <td>{1}</td>
				        </tr>";
        sb.AppendFormat(html, "Country", country);
        sb.AppendFormat(html, "City", city);
        if (!companyAddress.StreetAddress.IsNullOrEmpty())
            sb.AppendFormat(html, "Street Address", companyAddress.StreetAddress.HtmlEncode());
        if(!companyAddress.ZipCode.IsNullOrEmpty())
            sb.AppendFormat(html, "Zip Code", companyAddress.ZipCode.HtmlEncode());
        if (!companyAddress.Phone.IsNullOrEmpty())
            sb.AppendFormat(html, "Phone", companyAddress.Phone.HtmlEncode());
        if (!companyAddress.Fax.IsNullOrEmpty())
            sb.AppendFormat(html, "Fax", companyAddress.Fax.HtmlEncode());
        if (!companyAddress.Email.IsNullOrEmpty())
            sb.AppendFormat(html, "Email", companyAddress.Email);
        ltrAddress.Text = sb.ToString();
    }
    private void BindBillingAddress(Address billingAddress)
    {
        //ddlBillingCountry.SetSelectedItem(billingAddress.City.CountryID.ToString());
        //ddlBillingCountry_SelectedIndexChanged(ddlCountry, EventArgs.Empty);
        //ddlBillingCity.SetSelectedItem(billingAddress.CityID.ToString());
        //txtBillingPhone.Text = billingAddress.Phone;
        //txtBillingZipCode.Text = billingAddress.ZipCode;
        //txtBillingFax.Text = billingAddress.Fax;
        //txtBillingEmail.Text = billingAddress.Email;
        //txtBillingStreetAddress.Text = billingAddress.StreetAddress;
        //chkIsBillingAddress.Checked = false;
    }
    protected String GetPhotoUrl(object fileName)
    {
        String file = NullHandler.GetString(fileName);
        if (!file.IsNullOrEmpty())
        {
            return String.Format("<img class='ContactPhtoto' src='{0}/{1}' alt='{1}' title='{1}'/>", AppConstants.CONTACT_PHOTO, file);
        }
        return String.Empty;
    }
    /// <summary>
    /// Determines Whether this customer has certain type of project or not.
    /// </summary>
    /// <param name="propertyTypeID"></param>
    /// <returns></returns>
    protected bool HasProject(int propertyTypeID)
    {
        BtcHousingEntities context = new BtcHousingEntities();
        int projectCount = context.Projects.Count(P => P.CustomerID == _CustomerID && P.PropertyTypeID == propertyTypeID && P.PackageSubscription.ExpireDate >= DateTime.Now && !P.IsDeleted && P.Customer.IsApproved && !P.Customer.IsDeleted);
        return projectCount > 0;
    }

    [WebMethod]
    public static bool SendQueryToCustomer(App.CustomEntity.Message message)
    {
        if (message != null)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            Message entity = new Message();
            entity.CustomerID = message.CustomerID;
            entity.Phone = message.Phone;
            entity.FromEmail = message.FromEmail;
            entity.Subject = message.Subject;
            entity.SenderMessage = message.SenderMessage;
            entity.FirstName = message.FirstName;
            entity.LastName = message.LastName;
            entity.Address = message.Address;
            entity.IsSent = false;
            entity.Created = DateTime.Now;
            entity.Modified = DateTime.Now;

            ///TODO: Need to Send the Email to the corresponding customer instead of just saving it.

            context.AddToMessages(entity);
            context.SaveChanges();

            ///Send Email Notification            
            ///Get Company Email Addresses
            var addresses = from P in context.Addresses where P.CustomerID == message.CustomerID select P;
            StringBuilder companyEmail = new StringBuilder(10);
            foreach (Address address in addresses)
            {
                if (companyEmail.Length == 0 && !address.Email.IsNullOrEmpty())
                    companyEmail.Append(address.Email);
                else if (companyEmail.Length > 0 && !address.Email.IsNullOrEmpty())
                    companyEmail.AppendFormat(", {0}", address.Email);
            }
            ///Get Company Contact Emails
            StringBuilder contactEmail = new StringBuilder();
            var contacts = from P in context.Contacts where P.CustomerID == message.CustomerID select P;
            foreach (Contact contact in contacts)
            {
                if (contactEmail.Length == 0 && !contact.Email.IsNullOrEmpty())
                    contactEmail.Append(contact.Email);
                else if (contactEmail.Length > 0 && !contact.Email.IsNullOrEmpty())
                    contactEmail.AppendFormat(", {0}", contact.Email);
            }
            ///Build the Email Message
            StringBuilder emailTemplate = new StringBuilder(WebUtil.ReadEmailTemplate(AppConstants.EmailTemplate.COMMON));
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Dear Subscriber,<br/>");
            sb.AppendFormat("An User has sent you a query from {0}.<br /><br />", ConfigReader.ProviderCompany);
            sb.AppendFormat("<b><u>User Information:</u><br /></b>");
            sb.AppendFormat("<b>First Name:</b> {0}<br />", message.FirstName.HtmlEncode());
            sb.AppendFormat("<b>Last Name:</b> {0}<br />", message.LastName.HtmlEncode());
            sb.AppendFormat("<b>Email:</b> {0}<br />", message.FromEmail.HtmlEncode());
            sb.AppendFormat("<b>Address:</b> {0}<br />", message.Address.IsNullOrEmpty() ? "NA" : WebUtil.FormatText(message.Address));
            sb.AppendFormat("<b>Phone:</b> {0}<br />", message.Phone.IsNullOrEmpty() ? "NA" : message.Phone.HtmlEncode());
            sb.AppendFormat("<b>Subject:</b> {0}<br />", message.Subject.HtmlEncode());
            sb.AppendFormat("<b>Message:</b> {0}<br />", message.SenderMessage.HtmlEncode());


            emailTemplate.Replace(AppConstants.ETConstants.DOMAIN, WebUtil.GetDomainAddress());
            emailTemplate.Replace(AppConstants.ETConstants.MESSAGE, sb.ToString());
            String subject = String.Format("Your have a query from {0}", ConfigReader.ProviderCompany);
            if (companyEmail.Length > 0 || contactEmail.Length > 0)
            {
                if (companyEmail.Length > 0 && contactEmail.Length > 0)
                    WebUtil.SendMail(message.FromEmail, companyEmail.ToString(), String.Empty, contactEmail.ToString(), subject, emailTemplate.ToString());
                else if (companyEmail.Length > 0 && contactEmail.Length == 0)
                    WebUtil.SendMail(message.FromEmail, companyEmail.ToString(), String.Empty, String.Empty, subject, emailTemplate.ToString());
                else if (companyEmail.Length == 0 && contactEmail.Length > 0)
                    WebUtil.SendMail(message.FromEmail, contactEmail.ToString(), String.Empty, String.Empty, subject, emailTemplate.ToString());
            }


            return true;
        }
        return false;
    }
}